{% extends 'charts/base.html' %}

{% block options %}
    <ul class="nav ace-nav">
        <li>
            <div class="dropdown">
                <button class="btn btn-sm btn-pink dropdown-toggle" type="button" id="add_zixuan_menu"
                        data-toggle="dropdown"
                        aria-haspopup="true" aria-expanded="true">
                    <i class="ace-icon fa fa-heart"></i>
                    自选
                    <span class="caret"></span>
                </button>
                <ul class="dropdown-menu" id="zixuan_zx_names" aria-labelledby="add_zixuan_menu">
                    <li>
                        <div class="checkbox">
                            <label>
                                <input name="form-field-checkbox" type="checkbox" class="ace">
                                <span class="lbl">我的持仓</span>
                            </label>
                        </div>
                    </li>
                </ul>
            </div>
        </li>
        <li>
            <button class="btn btn-sm btn-purple" id="shuaxin" type="button" value="0">开启自动刷新</button>
        </li>
        <li>
            <button class="btn btn-sm btn-purple" type="button" id="import_stocks">导入股票代码</button>
        </li>
        <li>
            <div class="input-group" style="width: 200px;">
                <input type="text" class="form-control search-query" id="search_code" data-name=""
                       placeholder="StockCode" style="height: 34px; margin-top: 5px;">
                <span class="input-group-btn">
                    <button type="button" class="btn btn-purple btn-sm" id="stock_ok">展示</button>
                </span>
            </div>
        </li>


    </ul>
{% endblock %}

{% block sidebar %}
    <div class="tabbable">
        <ul class="nav nav-tabs" id="myTab">
            <li class="active">
                <a data-toggle="tab" href="#tab-stocks" aria-expanded="true">
                    股票列表
                </a>
            </li>

            <li class="">
                <a data-toggle="tab" href="#tab-jhs" aria-expanded="false">
                    机会列表
                </a>
            </li>

        </ul>

        <div class="tab-content">
            <div id="tab-stocks" class="tab-pane fade active in">
                <div class="btn-group btn-corner">
                    {% for zx in zx_list %}
                        <button class="btn btn-sm btn-info btn_zixuan"
                                data-zxname="{{ zx.name }}">{{ zx.short_name }}</button>
                    {% endfor %}
                </div>
                <div class="from-group">
                    <input class="form-control" id="stock_search" placeholder="Search" type="text"/>
                </div>

                <div class="stocks_list">
                    <div>
                        <ul class="nav nav-list" id="my_stocks">

                        </ul><!-- /.nav-list -->
                    </div>
                </div>
            </div>

            <div id="tab-jhs" class="tab-pane fade">
                <div class="stocks_list">
                    <ul class="list-group" id="jhs_ul">
                        <li class="list-group-item">Loading</li>
                    </ul>
                </div>

            </div>
        </div>
    </div>



{% endblock %}

{% block content %}
    {% include 'charts/options.html' %}

    <div class="col-lg-12">
        <div class="btn-toolbar" role="toolbar" aria-label="配置选项">
            <div class="btn-group btn-group-xs btn-corner" role="group" id="zq_high">
                <button type="button" class="btn btn-xs btn-default" data-zq="y">Year</button>
                <button type="button" class="btn btn-xs btn-default" data-zq="m">Month</button>
                <button type="button" class="btn btn-xs btn-default" data-zq="w">Week</button>
                <button type="button" class="btn btn-xs btn-default" data-zq="d">Day</button>
                <button type="button" class="btn btn-xs btn-default" data-zq="120m">120M</button>
                <button type="button" class="btn btn-xs btn-default" data-zq="60m">60M</button>
                <button type="button" class="btn btn-xs btn-default" data-zq="30m">30M</button>
                <button type="button" class="btn btn-xs btn-default" data-zq="15m">15M</button>
                <button type="button" class="btn btn-xs btn-default" data-zq="5m">5M</button>
                <button type="button" class="btn btn-xs btn-default" data-zq="1m">1M</button>
            </div>

            <div class="input-group pull-right form-group-sm" style="width: 200px;margin-right: 50px;">
                <input type="text" class="form-control datetime" value="" id="kline_dt_high"/>
                <span class="input-group-addon"><i class="fa fa-clock-o bigger-110"></i></span>
            </div>
        </div>
        <div id="kline_high" class="kline_chart" style="width:100%; min-height: 320px;"></div>
    </div>

    <div class="col-lg-12">
        <div class="btn-toolbar" role="toolbar" aria-label="配置选项">
            <div class="btn-group btn-group-xs btn-corner" role="group" id="zq_low">
                <button type="button" class="btn btn-xs btn-default" data-zq="y">Year</button>
                <button type="button" class="btn btn-xs btn-default" data-zq="m">Month</button>
                <button type="button" class="btn btn-xs btn-default" data-zq="w">Week</button>
                <button type="button" class="btn btn-xs btn-default" data-zq="d">Day</button>
                <button type="button" class="btn btn-xs btn-default" data-zq="120m">120M</button>
                <button type="button" class="btn btn-xs btn-default" data-zq="60m">60M</button>
                <button type="button" class="btn btn-xs btn-default" data-zq="30m">30M</button>
                <button type="button" class="btn btn-xs btn-default" data-zq="15m">15M</button>
                <button type="button" class="btn btn-xs btn-default" data-zq="5m">5M</button>
                <button type="button" class="btn btn-xs btn-default" data-zq="1m">1M</button>
            </div>

            <div class="input-group pull-right form-group-sm" style="width: 200px;margin-right: 50px;">
                <input type="text" class="form-control datetime" value="" id="kline_dt_low"/>
                <span class="input-group-addon"><i class="fa fa-clock-o bigger-110"></i></span>
            </div>
        </div>
        <div id="kline_low" class="kline_chart" style="width:100%; min-height: 320px;"></div>
    </div>
    <div style="width:100%; clear: both;">
        <p>行业信息：<span class="hy_list"></span></p>
        <p>概念信息：<span class="gn_list"></span></p>
    </div>
{% endblock %}


{% block js %}
    <script type="text/javascript">
        $(
            function () {
                var chart_high = getClientHeight() - (45 + 8 + 34);

                $('.stocks_list').ace_scroll({
                    size: 600
                });

                var code = 'HK.800000';
                var name = '恒生指数';
                var config = {
                    'high': {
                        'frequency': 'd',
                        'kline_dt': ''
                    },
                    'low': {
                        'frequency': '30m',
                        'kline_dt': ''
                    },
                }

                var url = window.location.href;
                if (url.split('#').length === 2) {
                    code = url.split('#')[1]
                }

                var intervalId;

                config['high']['chart'] = echarts.init(document.getElementById('kline_high'), 'dark', {renderer: 'canvas'});
                config['low']['chart'] = echarts.init(document.getElementById('kline_low'), 'dark', {renderer: 'canvas'});

                $('.datetime').datetimepicker({
                    format: 'YYYY-MM-DD HH:mm:ss',//use this option to display seconds
                    icons: {
                        time: 'fa fa-clock-o',
                        date: 'fa fa-calendar',
                        up: 'fa fa-chevron-up',
                        down: 'fa fa-chevron-down',
                        previous: 'fa fa-chevron-left',
                        next: 'fa fa-chevron-right',
                        today: 'fa fa-arrows ',
                        clear: 'fa fa-trash',
                        close: 'fa fa-times'
                    }
                });

                // 周期与配置的选择
                var cookie_pre = '_hk';
                var cl_setting = {
                    'fx_qj': 'fx_qj_k',
                    'fx_bh': 'fx_bh_dingdi',
                    'bi_type': 'bi_type_new',
                    'bi_bzh': 'bi_bzh_yes',
                    'bi_fx_cgd': 'bi_fx_cgd_no',
                    'bi_qj': 'bi_qj_ck',
                    'xd_bzh': 'xd_bzh_yes',
                    'xd_qj': 'xd_qj_dd',
                    'zslx_bzh': 'zslx_bzh_no',
                    'zslx_qj': 'zslx_qj_dd',
                    'zs_bi_type': 'zs_type_dn',
                    'zs_xd_type': 'zs_type_dn',
                    'zs_qj': 'zs_qj_dd',
                    'zs_wzgx': 'zs_wzgx_zgd',
                    'show_bi_zs': '1',
                    'show_xd_zs': '1',
                    'show_bi_mmd': '1',
                    'show_xd_mmd': '1',
                    'show_bi_bc': '1',
                    'show_xd_bc': '1',
                    'show_ma': '1',
                    'show_boll': '1',
                    'show_max_chart': '1',
                    'idx_macd_fast': 12,
                    'idx_macd_slow': 26,
                    'idx_macd_signal': 9,
                    'idx_boll_period': 20,
                    'idx_ma_period': 5,
                }
                for (let _k in cl_setting) {
                    if ($.cookie(cookie_pre + '_' + _k) !== undefined) {
                        cl_setting[_k] = $.cookie(cookie_pre + '_' + _k);
                    }
                    let _v = cl_setting[_k];
                    let obj = $('#' + _k);
                    if (obj.attr('type') === 'text') {
                        obj.val(_v);
                    }
                    if (obj.attr('type') === 'checkbox') {
                        obj.attr('checked', _v === '1');
                    }
                    if (obj.attr('type') === 'select') {
                        obj.find("option[value='" + _v + "']").attr("selected", true);
                    }
                }
                $('.chart_setting input,select').change(function () {
                    let _key = $(this).attr('id');
                    let _type = $(this).attr('type');
                    let _val = $(this).val();
                    if (_type === 'checkbox') {
                        _val = $(this).is(':checked') ? '1' : '0';
                    }
                    cl_setting[_key] = _val;
                    $.cookie(cookie_pre + '_' + _key, cl_setting[_key], {expires: 999});
                    console.log('setting change key ' + _key + ' val ' + _val);
                    if (_key === 'show_max_chart') {
                        chart_show_height(_val);
                    } else {
                        $.message({
                            message: '缠论配置变更，需重新点击当前周期更新图表数据',
                            type: 'success'
                        });
                    }
                });

                function chart_show_height(_type) {
                    if (_type === '0') {
                        $('#kline_high').css('height', chart_high / 2);
                        $('#kline_low').css('height', chart_high / 2);
                    } else {
                        $('#kline_high').css('height', chart_high);
                        $('#kline_low').css('height', chart_high);
                    }
                    config['high']['chart'].resize();
                    config['low']['chart'].resize();
                }

                chart_show_height(cl_setting['show_max_chart']);

                {% for level in show_level %}
                    if ($.cookie(cookie_pre + '_frequency_{{ level }}') !== undefined) {
                        config['{{ level }}']['frequency'] = $.cookie(cookie_pre + '_frequency_{{ level }}');
                    }
                    $('#zq_{{ level }}').find('[data-zq="' + config['{{ level }}']['frequency'] + '"]').addClass('btn-primary');

                    $('#zq_{{ level }} button').click(function () {
                        $('#zq_{{ level }} button').removeClass('btn-primary');
                        $(this).addClass('btn-primary');
                        config['{{ level }}']['frequency'] = $(this).attr('data-zq');
                        $.cookie(cookie_pre + '_frequency_{{ level }}', config['{{ level }}']['frequency'], {expires: 999});
                        fetchData(code, config['{{ level }}'], false);
                    });
                    $('#kline_dt_{{ level }}').blur(function () {
                        if ($(this).val() === config['{{ level }}']['kline_dt']) {
                            return false
                        }
                        config['{{ level }}']['kline_dt'] = $(this).val();
                        fetchData(code, config['{{ level }}'], false);
                    });

                {% endfor %}


                // 定时刷新
                $('#shuaxin').click(function () {
                    var val = $(this).attr('value');
                    if (val === '0') {
                        // 开启自动更新
                        $(this).attr('value', '1');
                        $(this).text('关闭自动更新');
                        intervalId = setInterval(function () {
                            fetchData(code, config['high'], true);
                            fetchData(code, config['low'], true);
                        }, 30000);
                    }
                    if (val === '1') {
                        // 关闭自动更新
                        $(this).attr('value', '0');
                        $(this).text('开启自动更新');
                        clearInterval(intervalId);
                    }
                });

                // 手动输入code显示
                $('#stock_ok').click(function () {
                    var stock_code = $('#search_code').val();
                    var stock_name = $('#search_code').attr('data-name');
                    if (stock_code !== '') {
                        code = stock_code;
                        name = stock_name;
                        fetchData(code, config['high'], false);
                        fetchData(code, config['low'], false);
                        stock_plate(code);
                        zixuan_code_query_zx_names(code);
                    }
                });

                // 股票搜索
                $('#search_code').autocomplete({
                    minChars: 2,
                    serviceUrl: "/search_code?market=hk",
                    dataType: 'json',
                    deferRequestBy: 500,
                    onSelect: function (suggestion) {
                        $('#search_code').val(suggestion.data);
                        $('#search_code').attr('data-name', suggestion.name);
                    }
                });

                // 批量导入股票列表
                $('#import_stocks').click(function () {
                    var json = prompt('请输入股票列表 JSON 数据：');
                    if (json === '') {
                        return false;
                    }
                    var stocks = eval('(' + json + ')')
                    $('#my_stocks').html('');
                    for (var i = 0; i < stocks.length; i++) {
                        var stock = stocks[i];
                        $('#my_stocks').append('<li class="code" data-code="' + stock['code'] + '" data-name="' + stock['name'] + '"><a href="#' + stock['code'] + '"><span class="menu-text">' + stock['code'] + ' / ' + stock['name'] + '</span></a></li>');
                    }
                    $('#stock_search').quicksearch('#my_stocks li');
                    return true;
                });

                // 点击切换股票行情
                $("body").delegate('.code', 'click', function () {
                    $('#my_stocks li').removeClass('active');
                    $(this).addClass('active');
                    code = $(this).attr('data-code');
                    name = $(this).attr('data-name');
                    fetchData(code, config['high'], false);
                    fetchData(code, config['low'], false);
                    stock_plate(code);
                    zixuan_code_query_zx_names(code);
                });
                // 板块点击事件
                $("body").delegate('.plate', 'click', function () {
                    var hy_code = $(this).attr('data-hycode');
                    $.ajax({
                        type: "GET",
                        url: "/hk/plate_stocks?code=" + hy_code,
                        dataType: 'json',
                        success: function (result) {
                            if (result['code'] == 200) {
                                $('#my_stocks').html('');
                                for (var i = 0; i < result['data'].length; i++) {
                                    var stock = result['data'][i];
                                    $('#my_stocks').append('<li class="code" data-code="' + stock['code'] + '" data-name="' + stock['name'] + '"><a href="#' + stock['code'] + '"><span class="menu-text">' + stock['code'] + ' / ' + stock['name'] + '</span></a></li>');
                                }
                                $('#stock_search').quicksearch('#my_stocks li');
                            }
                        }
                    });
                });


                // 请求 Kline 方法
                function fetchData(code, show_config, update = false) {
                    $('#loading').loading({theme: 'dark'});

                    let post_data = {
                        'code': code,
                        'frequency': show_config['frequency'],
                        'kline_dt': show_config['kline_dt']
                    }
                    for (let _k in cl_setting) {
                        post_data[_k] = cl_setting[_k];
                    }
                    $.ajax({
                        type: "POST",
                        url: "/hk/kline",
                        data: post_data,
                        success: function (result) {
                            var re_obj = (new Function("return " + result))();
                            if (update === false) {
                                show_config['chart'].clear();
                            }
                            show_config['chart'].setOption(re_obj);
                            {#chart.setOption(result.data);#}
                            $('#loading').loading('stop');
                        }

                    });
                }

                // 获取股票行业与概念信息
                function stock_plate(code) {
                    $.ajax({
                        type: "GET",
                        url: "/hk/plate?code=" + code,
                        dataType: 'json',
                        success: function (result) {
                            if (result['code'] === 200) {
                                hy_list = '';
                                gn_list = '';
                                for (let i = 0; i < result['data']['HY'].length; i++) {
                                    hy = result['data']['HY'][i];
                                    hy_list += '<a href="javascript:void(0);" class="plate" data-hycode="' + hy['code'] + '">' + hy['name'] + '</a>  / '
                                }
                                for (let i = 0; i < result['data']['GN'].length; i++) {
                                    gn = result['data']['GN'][i];
                                    gn_list += '<a href="javascript:void(0);" class="plate" data-hycode="' + gn['code'] + '">' + gn['name'] + '</a>  / '
                                }
                                $('.hy_list').html(hy_list);
                                $('.gn_list').html(gn_list);
                            }
                        }
                    });
                    return true
                }

                // 机会列表的展示
                function jhs_list_show() {
                    $.ajax({
                        type: "GET",
                        url: "/hk/jhs",
                        dataType: 'json',
                        success: function (result) {
                            if (result['code'] === 200) {
                                $('#jhs_ul').html('');
                                for (let i = 0; i < result['data'].length; i++) {
                                    jh = result['data'][i];
                                    $('#jhs_ul').append('<li class="list-group-item"><p class="list-group-item-heading"><a href="javascript:void(0);" class="code" data-code="' + jh['code'] + '" data-name="' + jh['name'] + '">' + jh['name'] + '</a> <span>' + jh['frequency'] + '</span></p> <p class="list-group-item-text">' + jh['jh_type'] + ' <br/>' + jh['is_done'] + ' ' + jh['is_td'] + '<br/> ' + jh['datetime_str'] + '</p></li>');
                                }
                            }
                        }
                    });
                }

                // 自选切换
                $('.btn_zixuan').click(function () {
                    $('.btn_zixuan').removeClass('btn-success');
                    $(this).addClass('btn-success');
                    var zx_name = $(this).attr('data-zxname');
                    $.ajax({
                        type: "GET",
                        url: "/zixuan/stocks?market_type=hk&zx_name=" + zx_name,
                        dataType: 'json',
                        success: function (result) {
                            if (result['code'] === 200) {
                                $('#my_stocks').html('');
                                for (var i = 0; i < result['data'].length; i++) {
                                    var stock = result['data'][i];
                                    $('#my_stocks').append('<li class="code" data-code="' + stock['code'] + '" data-name="' + stock['name'] + '"><a href="#' + stock['code'] + '"><span class="menu-text">' + stock['code'] + ' / ' + stock['name'] + '</span></a></li>');
                                }
                                $('#stock_search').quicksearch('#my_stocks li');
                            }
                        }
                    });
                });


                // 根据代码，查询自选分组
                function zixuan_code_query_zx_names(code) {
                    $.ajax({
                        type: "GET",
                        url: "/zixuan/code_zx_names?market_type=hk&code=" + code,
                        dataType: 'json',
                        success: function (result) {
                            if (result['code'] === 200) {
                                $('#zixuan_zx_names').html('');
                                for (let i = 0; i < result['data'].length; i++) {
                                    var zx_name = result['data'][i];
                                    var checked = zx_name['exists'] === 1 ? 'checked' : '';
                                    $('#zixuan_zx_names').append('<li><div class="checkbox"><label>' +
                                        '<input name="zx_name" type="checkbox" data-zx-name="' + zx_name['zx_name'] + '" ' + checked + ' class="ace opt_zx">' +
                                        '<span class="lbl">' + zx_name['zx_name'] + '</span>' +
                                        '</label></div></li>');
                                }
                            }
                        }
                    });
                }

                // 自选操作
                $("body").delegate('.opt_zx', 'change', function () {
                    var checked = $(this).prop('checked');
                    var zx_name = $(this).attr('data-zx-name');
                    var opt = checked === true ? 'add' : 'del';
                    $.ajax({
                        type: "GET",
                        url: '/zixuan/opt?market_type=hk&zx_name=' + zx_name + '&opt=' + opt + '&code=' + code + '&name=' + name,
                        dataType: 'json',
                        success: function (result) {
                            let msg = '';
                            if (opt === 'add') {
                                msg = '添加自选组 ' + zx_name + ' 成功';
                            } else {
                                msg = '删除自选组 ' + zx_name + ' 成功';
                            }

                            if (result['code'] === 200) {
                                $.message({
                                    message: msg,
                                    type: 'success'
                                });
                            } else {
                                $.message({
                                    message: '操作自选失败',
                                    type: 'error'
                                });
                            }
                        }
                    });
                });


                // 自动触发一次
                $('.btn_zixuan')[0].click();

                fetchData(code, config['high'], true);
                fetchData(code, config['low'], true);
                zixuan_code_query_zx_names(code);
                stock_plate(code);

                jhs_list_show();
                setInterval(jhs_list_show, 60000);
            }
        );
    </script>
{% endblock %}